<template>
  <el-card :style="`height:${view.height - 140}px;`">
    <el-row class="filter-row" style="margin-bottom: 20px" :gutter="20">
      <!-- 样本类型 -->
      <el-col :span="6">
        <span>样本类型</span>&emsp;
        <el-select
          style="width: 80%"
          v-model="filters.sampleType"
          placeholder="选择样本类型"
          clearable
        >
          <el-option
            v-for="item in sampleTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>

      <!-- 分辨率 -->
      <el-col :span="6">
        <span>分辨率</span>&emsp;
        <el-select
          style="width: 80%"
          v-model="filters.resolutions"
          multiple
          placeholder="选择分辨率"
          clearable
        >
          <el-option
            v-for="item in resolutions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>

      <!-- 样本大小 -->
      <el-col :span="6">
        <span>样本大小</span>&emsp;
        <el-select
          style="width: 80%"
          v-model="filters.sampleSizes"
          multiple
          placeholder="选择样本大小"
          clearable
        >
          <el-option
            v-for="item in sampleSizes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>

      <!-- 查询按钮 -->
      <el-col :span="6">
        <el-button type="primary" @click="submitFilters">样本查询</el-button>
      </el-col>
    </el-row>

    <!-- 样本表格 -->
    <el-table
      :data="filteredSamples"
      style="width: 100%"
      :border="true"
      :style="`height:${view.height - 340}px;margin:0 0 20px`"
      size="small"
    >
      <el-table-column
        label="节点名称"
        prop="NodeName"
        :align="'center'"
      ></el-table-column>
      <el-table-column
        label="前时相影像"
        prop="QFileName"
        :align="'center'"
        width="340"
      ></el-table-column>
      <el-table-column
        label="后时相影像"
        prop="HFileName"
        :align="'center'"
        width="340"

      ></el-table-column>
      <el-table-column
        label="标记矢量"
        prop="CHShpName"
        :align="'center'"
      ></el-table-column>
      <el-table-column
        label="标记字段"
        prop="ShpField"
        width=""
        :align="'center'"
      ></el-table-column>
      <el-table-column
        label="样本数量"
        prop="SampleCount"
        width=""
        :align="'center'"
      ></el-table-column>
      <el-table-column
        label="分辨率"
        prop="Res"
        width=""
        :align="'center'"
      ></el-table-column>
      <el-table-column
        label="样本大小"
        prop="Size"
        width=""
        :align="'center'"
      ></el-table-column>
      <el-table-column
        label="样本类型"
        prop="SampleType"
        :align="'center'"
      ></el-table-column>
      <el-table-column
        label="状态"
        prop="Status"
        width=""
        :align="'center'"
      ></el-table-column>
      <el-table-column label="操作" width="200" fixed="right" :align="'center'">
        <template #default="{ row }">
          <el-button
            size="small"
            type="success"
            plain
            @click="viewSampleDetail(row.OBJID)"
          >
            样本详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="filteredSamples.length > 0"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalSamples"
      @current-change="handlePageChange"
      layout="total, prev, pager, next, jumper"
    ></el-pagination>

    <!-- 样本详情弹窗 -->
    <el-dialog
      :modelValue="isDetailDialogVisible"
      title="样本详情"
      width="80%"
      :before-close="detailCloseHandler"
    >
      <el-table
        :data="sampleDetailData"
        style="width: 100%"
        :border="true"
        size="small"
      >
        <el-table-column
          :align="'center'"
          label="样本ID"
          prop="OBJID"
        ></el-table-column>
        <el-table-column
          :align="'center'"
          label="节点名称"
          prop="NodeName"
        ></el-table-column>
        <el-table-column :align="'center'" width="500" label="文件A名称" prop="NameA">
          <template #default="{ row }">
            <el-image
              style="width: 500px; height: 500px"
              :src="`${baseUrl}${row.NameA}.jpg`"
              :fit="'fill'"
            />
          </template>
        </el-table-column>
        <el-table-column :align="'center'" width="500" label="文件B名称" prop="NameB">
          <template #default="{ row }">
            <el-image
              style="width: 500px; height: 500px"
              :src="`${baseUrl}${row.NameB}.jpg`"
              :fit="'fill'"
            />
          </template>
        </el-table-column>
        <el-table-column :align="'center'" width="500" label="文件L名称" prop="NameL">
          <template #default="{ row }">
            <el-image
              style="width: 500px; height: 500px"
              :src="`${baseUrl}${row.NameL}.jpg`"
              :fit="'fill'"
            />
          </template>
        </el-table-column>
       <!--  <el-table-column
          :align="'center'"
          label="创建时间"
          prop="CreateTime"
        ></el-table-column> -->
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="sampleDetailData.length > 0"
        :current-page="sampleDetailPage"
        :page-size="sampleDetailPageSize"
        :total="sampleDetailTotal"
        @current-change="handleDetailPageChange"
        layout="total, prev, pager, next, jumper"
      ></el-pagination>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";

const baseUrl = "http://localhost:3005/images/";
// Managing the window height
const view = reactive({
  height: window.innerHeight,
});

// 数据模型和筛选条件
const filters = reactive({
  sampleType: "",
  resolutions: [],
  sampleSizes: [],
  page: 1,
  limit: 10,
});

// 获取到的筛选选项
const sampleTypes = ref([]);
const resolutions = ref([]);
const sampleSizes = ref([]);

// 页码与分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalSamples = ref(0);

// 样本数据
const filteredSamples = ref([]);
const currentSampleId = ref();

// 样本详情数据
const sampleDetailData = ref([]);
const sampleDetailPage = ref(1);
const sampleDetailPageSize = ref(2);
const sampleDetailTotal = ref(0);

// 控制样本详情弹窗显示
const isDetailDialogVisible = ref(false);

// 模拟数据（包含新增的节点名称字段和更多记录）
const mockSamples = [
  {
    OBJID: 1,
    NodeName: "新疆阿勒泰",
    QFileName: "XJ20230601",
    HFileName: "XJ20230701",
    CHShpName: "XJ_Vector_001",
    ShpField: "Land_Use",
    SampleCount: 502,
    Res: "2m",
    Size: "256x256",
    SampleType: "人为活动",
    Status: "已完成"
  },
  {
    OBJID: 2,
    NodeName: "海南",
    QFileName: "HN20230501",
    HFileName: "HN20230601",
    CHShpName: "HN_Vector_001",
    ShpField: "Land_Cover",
    SampleCount: 735,
    Res: "2m",
    Size: "512x512",
    SampleType: "人为活动",
    Status: "已完成"
  },
  {
    OBJID: 3,
    NodeName: "云南",
    QFileName: "YN20230401",
    HFileName: "YN20230501",
    CHShpName: "YN_Vector_001",
    ShpField: "Forest_Cover",
    SampleCount: 623,
    Res: "2m",
    Size: "256x256",
    SampleType: "人为活动",
    Status: "处理中"
  },
  {
    OBJID: 4,
    NodeName: "浙江",
    QFileName: "ZJ20230301",
    HFileName: "ZJ20230401",
    CHShpName: "ZJ_Vector_001",
    ShpField: "Urban_Exp",
    SampleCount: 584,
    Res: "2m",
    Size: "512x512",
    SampleType: "人为活动",
    Status: "已完成"
  },
  {
    OBJID: 5,
    NodeName: "山西",
    QFileName: "SX20230201",
    HFileName: "SX20230301",
    CHShpName: "SX_Vector_001",
    ShpField: "Mining_Area",
    SampleCount: 412,
    Res: "2m",
    Size: "256x256",
    SampleType: "人为活动",
    Status: "已完成"
  },
  {
    OBJID: 6,
    NodeName: "广西",
    QFileName: "GX20230101",
    HFileName: "GX20230201",
    CHShpName: "GX_Vector_001",
    ShpField: "Water_Body",
    SampleCount: 385,
    Res: "2m",
    Size: "256x256",
    SampleType: "水体变化",
    Status: "处理中"
  },
  {
    OBJID: 7,
    NodeName: "重庆",
    QFileName: "CQ20221201",
    HFileName: "CQ20230101",
    CHShpName: "CQ_Vector_001",
    ShpField: "Building",
    SampleCount: 254,
    Res: "2m",
    Size: "512x512",
    SampleType: "人为活动",
    Status: "已完成"
  },
  {
    OBJID: 8,
    NodeName: "山东",
    QFileName: "SD20221101",
    HFileName: "SD20221201",
    CHShpName: "SD_Vector_001",
    ShpField: "Crop_Land",
    SampleCount: 367,
    Res: "2m",
    Size: "256x256",
    SampleType: "人为活动",
    Status: "已完成"
  },
  {
    OBJID: 9,
    NodeName: "江苏",
    QFileName: "JS20221001",
    HFileName: "JS20221101",
    CHShpName: "JS_Vector_001",
    ShpField: "Coastal_Zone",
    SampleCount: 298,
    Res: "2m",
    Size: "512x512",
    SampleType: "人为活动",
    Status: "处理中"
  },
  {
    OBJID: 10,
    NodeName: "甘肃",
    QFileName: "GS20220901",
    HFileName: "GS20221001",
    CHShpName: "GS_Vector_001",
    ShpField: "Desert_Area",
    SampleCount: 201,
    Res: "2m",
    Size: "256x256",
    SampleType: "人为活动",
    Status: "已完成"
  }
];

// 模拟样本详情数据
const mockSampleDetails = {
  1: [
    { OBJID: 101, NodeName: "新疆阿勒泰", NameA: "XJ_Sample_A_001", NameB: "XJ_Sample_B_001", NameL: "XJ_Sample_L_001" },
    { OBJID: 102, NodeName: "新疆阿勒泰", NameA: "XJ_Sample_A_002", NameB: "XJ_Sample_B_002", NameL: "XJ_Sample_L_002" },
    { OBJID: 103, NodeName: "新疆阿勒泰", NameA: "XJ_Sample_A_003", NameB: "XJ_Sample_B_003", NameL: "XJ_Sample_L_003" },
    { OBJID: 104, NodeName: "新疆阿勒泰", NameA: "XJ_Sample_A_004", NameB: "XJ_Sample_B_004", NameL: "XJ_Sample_L_004" }
  ],
  2: [
    { OBJID: 201, NodeName: "海南", NameA: "HN_Sample_A_001", NameB: "HN_Sample_B_001", NameL: "HN_Sample_L_001" },
    { OBJID: 202, NodeName: "海南", NameA: "HN_Sample_A_002", NameB: "HN_Sample_B_002", NameL: "HN_Sample_L_002" },
    { OBJID: 203, NodeName: "海南", NameA: "HN_Sample_A_003", NameB: "HN_Sample_B_003", NameL: "HN_Sample_L_003" },
    { OBJID: 204, NodeName: "海南", NameA: "HN_Sample_A_004", NameB: "HN_Sample_B_004", NameL: "HN_Sample_L_004" }
  ],
  3: [
    { OBJID: 301, NodeName: "云南", NameA: "YN_Sample_A_001", NameB: "YN_Sample_B_001", NameL: "YN_Sample_L_001" },
    { OBJID: 302, NodeName: "云南", NameA: "YN_Sample_A_002", NameB: "YN_Sample_B_002", NameL: "YN_Sample_L_002" }
  ]
};

// 获取筛选条件选项
const fetchOptions = async () => {
  try {
    // 如果API不可用，使用模拟数据
    try {
      const typeResponse = await axios.post("/algorithmApi/mete/findByType", {
        Type: 3,
      });
      if (typeResponse.data.success) {
        sampleTypes.value = typeResponse.data.data.map((item) => ({
          label: item.label,
          value: item.value,
        }));
      }
    } catch (error) {
      // 使用模拟数据
      sampleTypes.value = [
        { label: "人为活动", value: "人为活动" },
        { label: "人为活动", value: "人为活动" },
        { label: "人为活动", value: "人为活动" },
        { label: "水体变化", value: "水体变化" },
        { label: "人为活动", value: "人为活动" }
      ];
    }

    try {
      const resolutionResponse = await axios.post(
        "/algorithmApi/mete/findByType",
        { Type: 2 }
      );
      if (resolutionResponse.data.success) {
        resolutions.value = resolutionResponse.data.data.map((item) => ({
          label: item.label,
          value: item.value,
        }));
      }
    } catch (error) {
      // 使用模拟数据
      resolutions.value = [
        { label: "2m", value: "2m" },
        { label: "5m", value: "5m" },
        { label: "10m", value: "10m" }
      ];
    }

    try {
      const sizeResponse = await axios.post("/algorithmApi/mete/findByType", {
        Type: 1,
      });
      if (sizeResponse.data.success) {
        sampleSizes.value = sizeResponse.data.data.map((item) => ({
          label: item.label,
          value: item.value,
        }));
      }
    } catch (error) {
      // 使用模拟数据
      sampleSizes.value = [
        { label: "256x256", value: "256x256" },
        { label: "512x512", value: "512x512" }
      ];
    }
  } catch (error) {
    ElMessage.error("数据加载失败");
  }
};

// 提交查询条件，调用查询接口
const submitFilters = async () => {
  try {
    // 尝试调用API
   /*  try {
      const response = await axios.post("/algorithmApi/sample/query", filters);
      if (response.data.success) {
        filteredSamples.value = response.data.data;
        totalSamples.value = response.data.total;
      } else {
        throw new Error("API调用失败");
      }
    } catch (error) { */
      // 使用模拟数据
      const filtered = mockSamples.filter(sample => {
        const typeMatch = !filters.sampleType || sample.SampleType === filters.sampleType;
        const resMatch = filters.resolutions.length === 0 || filters.resolutions.includes(sample.Res);
        const sizeMatch = filters.sampleSizes.length === 0 || filters.sampleSizes.includes(sample.Size);
        return typeMatch && resMatch && sizeMatch;
      });
      
      const start = (filters.page - 1) * filters.limit;
      const end = start + filters.limit;
      
      filteredSamples.value = filtered.slice(start, end);
      totalSamples.value = filtered.length;
    // }
  } catch (error) {
    ElMessage.error("查询失败: " + error.message);
  }
};

// 查看样本详情
const viewSampleDetail = async (sampleId: number) => {
  currentSampleId.value = sampleId;
  try {
    // 尝试调用API
    try {
      const response = await axios.get(`/algorithmApi/sample-detail/query`, {
        params: {
          CHID: currentSampleId.value,
          page: sampleDetailPage.value,
          limit: sampleDetailPageSize.value,
        },
      });

      if (response.data.success) {
        sampleDetailData.value = response.data.data;
        sampleDetailTotal.value = response.data.total;
        isDetailDialogVisible.value = true;
      } else {
        throw new Error("API调用失败");
      }
    } catch (error) {
      // 使用模拟数据
      const details = mockSampleDetails[sampleId] || [];
      const start = (sampleDetailPage.value - 1) * sampleDetailPageSize.value;
      const end = start + sampleDetailPageSize.value;
      
      sampleDetailData.value = details.slice(start, end);
      sampleDetailTotal.value = details.length;
      isDetailDialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error("获取样本详情失败: " + error.message);
  }
};

// 分页处理
const handlePageChange = (page: number) => {
  filters.page = page;
  currentPage.value = page;
  submitFilters();
};

// 样本详情分页处理
const handleDetailPageChange = (page: number) => {
  sampleDetailPage.value = page;
  viewSampleDetail(currentSampleId.value);
};

// 组件加载时获取筛选选项
onMounted(() => {
  fetchOptions();
  submitFilters();
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    view.height = window.innerHeight;
  });
});

const detailCloseHandler = function () {
  isDetailDialogVisible.value = false;
};
</script>

<style scoped>
.filter-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.el-form-item {
  margin-bottom: 15px;
}

/* 添加一些样式以提高表格可读性 */
.el-table {
/*   --el-table-border-color: #EBEEF5;
  --el-table-header-background-color: #F5F7FA; */
}

.el-table th {
  font-weight: bold;
  background-color: #F5F7FA;
}

.el-table td {
  padding: 8px 0;
}

/* 表格鼠标悬停效果 */
.el-table tr:hover > td {
  background-color: #F5F7FA;
}
</style>